package com.wolfsea.rvitemdecorationdemo.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.wolfsea.rvitemdecorationdemo.databinding.FragmentHomeBinding
import com.wolfsea.rvitemdecorationdemo.itemdecoration.HomeTimeLineItemDecoration
import com.wolfsea.rvitemdecorationdemo.rvadapter.HomeRvAdapter

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null

    private val binding get() = _binding!!

    private lateinit var mHomeRvAdapter: HomeRvAdapter
    private lateinit var mHomeRvItemDecoration: HomeTimeLineItemDecoration


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        val homeViewModel =
            ViewModelProvider(this).get(HomeViewModel::class.java)

        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root
        initData(binding, homeViewModel)
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    /*
    * 初始化数据
    * */
    private fun initData(binding: FragmentHomeBinding, viewModel: HomeViewModel) {

        val homeLayoutManager = LinearLayoutManager(context)

        mHomeRvAdapter = HomeRvAdapter()
        mHomeRvItemDecoration = HomeTimeLineItemDecoration(requireContext())

        viewModel.listSet.observe(viewLifecycleOwner) {
            mHomeRvAdapter.setDataSet(it)
        }

        binding.rvHome.apply {
            layoutManager = homeLayoutManager
            addItemDecoration(mHomeRvItemDecoration)
            adapter = mHomeRvAdapter
        }

        binding.clickBtn.setOnClickListener {
            mHomeRvItemDecoration.updateCurrentIndex(3)
            mHomeRvAdapter.notifyDataSetChanged()
        }
    }

}